package com.rpc.core.param;


import com.rpc.core.util.GsonUtil;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

//配置托管
public class ZkRemotingParams implements FactoryBean<RpcParams>, InitializingBean {

    private ZkClient client;

    private String path;

    private String url;

    private int timeout;

    private RpcParams params;

    private boolean isWrite = false;

    public void setWrite(boolean write) {
        isWrite = write;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public void setParams(RpcParams params) {
        this.params = params;
    }

    @Override
    public RpcParams getObject() throws Exception {
        return params;
    }

    @Override
    public Class<?> getObjectType() {
        return RpcParams.class;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.client = new ZkClient(this.url, this.timeout);

        if (!isWrite) {
            String data = (String) this.client.readData(path);
            params = GsonUtil.GsonToBean(data, RpcParams.class);

            if (params == null) {
                throw new RuntimeException("params init error");
            }
        } else {
            if (params == null) {
                throw new RuntimeException("params init error");
            }
            String gsonString = GsonUtil.GsonString(this.params);
            this.client.writeData(this.path, gsonString);
        }
    }


}
